import React, {
  LegacyRef,
  ReactElement,
  ReactNode,
  RefObject,
  useRef,
  useState,
} from 'react';
import {FlatList, ScrollView, Text, TouchableOpacity, View} from 'react-native';
import {ObserverView} from './ObserverView';
import {dpw12, dpw14, dpw40, dpw48} from '../constants';
import {ObserverText} from './ObserverText';
import {SvgLeft} from './svg';

interface ScrollHeadProps {
  renderItem: any;
  data: any[];
  title: string;
  navigation: any;
  listerTop?: Function;
  ListHeaderComponent?: ReactElement;
  stickyHeaderIndices?: number[];
  onEndReached?: any;
  onViewableItemsChanged?: any;
  initialNumToRender?: number;
}
export const ScrollHead = (props: ScrollHeadProps) => {
  const {renderItem, data, title, navigation, listerTop, ...rest} = props;
  const scrollViewRef = useRef(null);
  const viewRef = useRef<View>(null);

  const goBack = () => {
    if (navigation) {
      navigation.goBack();
    }
  };

  const handleScroll = (event: any) => {
    const offset = event.nativeEvent.contentOffset.y;
    const opacityValue = Math.max(0, offset) / 100;
    if (viewRef.current) {
      listerTop && listerTop(opacityValue);
      viewRef.current.setNativeProps({
        style: {opacity: opacityValue > 1 ? 1 : opacityValue},
      });
    }
  };

  return (
    <ObserverView style={{flex: 1, position: 'relative'}}>
      <TouchableOpacity
        style={{zIndex: 100, position: 'absolute', top: dpw14, left: dpw12}}
        onPress={goBack}>
        <SvgLeft />
      </TouchableOpacity>
      <ObserverView
        ref={viewRef}
        style={{
          opacity: 0,
          height: dpw48,
          flexDirection: 'row',
          alignItems: 'center',
          position: 'absolute',
          left: 0,
          top: 0,
          width: '100%',
          overflow: 'hidden',
          zIndex: 99,
        }}
        themeStyle={{backgroundColor: 'color_2'}}>
        <ObserverText
          style={{paddingLeft: dpw48}}
          tKey={title}
          type="head"
          numberOfLines={1}
          ellipsizeMode="tail"
        />
      </ObserverView>
      <FlatList
        ref={scrollViewRef}
        onScroll={handleScroll}
        scrollEventThrottle={16}
        data={data}
        renderItem={renderItem}
        keyExtractor={item => `${item.Id}`}
        onEndReachedThreshold={0.1}
        {...rest}
      />
    </ObserverView>
  );
};
